var viewer;

function loadFriends()
{
    var req;
    var params = {};
  
    try
    {
        //var idspec = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
        req = opensocial.newDataRequest();
          
        params[opensocial.DataRequest.PeopleRequestFields.MAX] = 9999;
        params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;

        //req.add(req.newFetchPersonRequest("VIEWER"), 'viewer');
        req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS", params), 'viewerFriends');
        //req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data');
        //req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData');

        req.send(onLoadFriends);
    }
    catch(err)
    {
        alert(err);
    }
}

function onLoadFriends(data)
{
    var viewerFriends;
    
    try
    {
        viewerFriends = data.get('viewerFriends').getData();

        //var friends = new Array();
  
        html = new Array();
        html.push('<select id="person">');
        
        viewerFriends.each(function(person)
        {
            html.push('<option value="' + person.getId() + '">' + person.getDisplayName() + "</option>");
            //friends[person.getId()] = person.getDisplayName();
        });
        
        html.push('</select>');
        document.getElementById('friends').innerHTML = html.join('');
    }
    catch (err)
    {
        alert(err);
    }
}

function loadViewer(callBack)
{
    var req;
    
    try
    {
        req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest("VIEWER"), 'viewer');
        
        req.send(callBack);
    }
    catch(err)
    {
        alert(err);
    }    
}


function desafiarAmigo(resp)
{
    var url;
    var data;
    var postdata;
    var params = {};
    var desafiado;
    var viewer;
    
    try
    {
        viewer = resp.get('viewer').getData();
        
        url = "http://infggadget.midia3.com.br/service/iniciarJogo.aspx";
        
        desafiado = document.getElementById('person');
        desafiado = desafiado.options[desafiado.selectedIndex];
        
        data =  {
                    id_desafiante : viewer.getId(), nome_desafiante : viewer.getDisplayName(), time_desafiante : "Flamengo",
                    id_desafiado : desafiado.value, nome_desafiado : desafiado.text, time_desafiado : "Vasco"
                };
        
        postdata = gadgets.io.encodeValues(data);
        
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
        params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
        params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
        params[gadgets.io.RequestParameters.POST_DATA]= postdata;
      
        gadgets.io.makeRequest(url, iniciarJogo, params);
    }
    catch (err)
    {
        alert(err);
    }
}

function iniciarJogo(obj)
{
    alert(obj);
    var jsondata = obj.data;
    var html = "";
    
    alert(jsondata);
    
    // Process returned JS object as an associative array
    for (var key in jsondata)
    {
        var value = jsondata[key];
        html += key + ": ";
        // If 'value' is an array, render its contents as a bulleted list
        if (value instanceof Array)
        {
            html += "<br /><ul>";
            for (var i = 0; i < value.length ; i++)
            {
                html += "<li>"+ jsondata.Hobbies[i] + "</li>";
            }
            html+= "</ul>";
        }  
        // If 'value' isn't an array, just write it out as a string
        else
        {
            html += value + "<br />";
        }      
    }
    
    document.getElementById('content_div').innerHTML = html;
}







function init() {
  loadFriends();
}


//function makeJSONRequest()
//{    
//      var params = {};
//      var url = "http://infggadget.midia3.com.br/service/service.aspx";
//      var data = { data1 : "teste", data2 : 123456 };
//      var postdata;
//      
//      postdata = gadgets.io.encodeValues(data);
//      
//      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
//      params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
//      params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
//      params[gadgets.io.RequestParameters.POST_DATA]= postdata;
//      //params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
//      
//      gadgets.io.makeRequest(url, response, params);
//}

//    function response(obj) { 
//      var jsondata = obj.data;
//      
//      alert("objeto: " + obj);
//      alert("conteudo: " + obj.data);
//      
//      var html = "";
//      // Process returned JS object as an associative array
//      for (var key in jsondata) {
//        var value = jsondata[key];
//        html += key + ": ";
//        // If 'value' is an array, render its contents as a bulleted list
//        if (value instanceof Array)
//        {
//          html += "<br /><ul>";
//          for (var i = 0; i < value.length ; i++)
//          {
//            html += "<li>"+ jsondata.Hobbies[i] + "</li>";
//          }
//          html+= "</ul>";
//        }  
//        // If 'value' isn't an array, just write it out as a string
//        else {        
//          html += value + "<br />";
//        }      
//      }               
//      document.getElementById('content_div').innerHTML = html;
//     }


//function makePOSTRequest(url, postdata) {
//   var params = {};
//   postdata = gadgets.io.encodeValues(postdata);

//   gadgets.io.makeRequest(url, response, params); 
//};
//function response(obj) {
//   output(obj.text); 
//};
//var data = {   data1 : "test",   data2 : 123456 }; 
//makePOSTRequest("http://example.com", data); 








//var t;
//var timer_is_on = false;
//var firtsLoad = true;

//function timedCount()
//{
//    var nut;
//    var friend;
//    
//    if (!firtsLoad)
//    {
//        if (document.getElementById('nut') != undefined && document.getElementById('nut') != null)
//            nut = document.getElementById('nut').value;
//        
//        if (document.getElementById('person') != undefined && document.getElementById('person') != null)
//            friend = document.getElementById('person').value;
//    }
//        
//    //alert('loading...');
//    
//    t = setTimeout("timedCount()", 5000);
//    
//    init();

//    if (!firtsLoad)
//    {
//        Select_Value_Set('nut', nut);
//        Select_Value_Set('person', person);
//    }
//    
//    firtsLoad = false;
//    //alert('loaded!');
//}

//function doTimer()
//{
//    if (!timer_is_on)
//    {
//        timer_is_on = true;
//        timedCount();
//    }
//}

//function Select_Value_Set(Id, Value)
//{
//    SelectObject = document.getElementById(Id);
//  
//    for(index = 0; index < SelectObject.length; index++)
//    {
//        if (SelectObject[index].value == Value)
//            SelectObject.selectedIndex = index;
//   }
//}





//var globalGivenGifts = {}; 
//var globalViewer = {};
//var globalFriends = {};

//function postActivity(nut, friend) {
//  var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];
//  
//  var title = globalViewer.getDisplayName() + ' gave ' + globalFriends[friend] + ' ' + options[nut];
//  var params = {};
//  params[opensocial.Activity.Field.TITLE] = title;
//  var activity = opensocial.newActivity(params);
//  opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
//}

//function updateReceivedList(viewer, data, friends) {
//  var viewerId = viewer.getId();
//  
//  var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];
//  
//  var html = new Array();
//  html.push('You have received:<ul>');
//  friends.each(function(person) {
//    var personData = data[person.getId()];
//    if (personData) {
//      var json = data[person.getId()]['gifts'];
//    
//      var gifts = {}
//      if (!json) {
//        gifts = {};
//      }
//      try {
//        gifts = gadgets.json.parse(gadgets.util.unescapeString(json));
//      } catch (e) {
//        gifts = {};
//      }
//    
//      for (i in gifts) {
//        if (+(i) > 0 && i == viewerId) {
//          html.push('<li>' + options[gifts[i]] + ' from ' + person.getDisplayName() + '</li>');
//        }
//      }
//    }
//  });
//  html.push('</ul>');
//  document.getElementById('received').innerHTML = html.join('');
//}

//function updateGiftList(viewer, data, friends) {
//  var json = data[viewer.getId()]['gifts'];
//  
//  if (!json) {
//    globalGivenGifts = {};
//  }
//  try {
//    globalGivenGifts = gadgets.json.parse(gadgets.util.unescapeString(json));
//  } catch (e) {
//    globalGivenGifts = {};
//  }
//  
//  var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];
//  
//  var html = new Array();
//  html.push('You have given:');
//  html.push('<ul>');
//  for (i in globalGivenGifts) {
//    if (+(i) > 0) {
//      html.push('<li>' + friends[i] + ' received ' + options[globalGivenGifts[i]] + '</li>');
//    }
//  }
//  html.push('</ul>');
//  document.getElementById('given').innerHTML = html.join('');
//}

//function giveGift() {
//  var nut = document.getElementById('nut').value;
//  var friend = document.getElementById('person').value;
//  
//  var params = {};
//  //params[opensocial.DataRequest.PeopleRequestFields.MAX] = 9999;
//  params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;
//  
//  globalGivenGifts[friend] = nut;
//  var json = gadgets.json.stringify(globalGivenGifts);
//  
//  var req = opensocial.newDataRequest();
//  req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'gifts', json));
//  req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
//  req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS', params), 'viewerFriends');
//  req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data');
//  req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData');
//  req.send(onLoadFriends);
//  
//  postActivity(nut, friend);
//}

//function makeOptionsMenu() {
//  var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];
//                 
//  var html = new Array();
//  html.push('<select id="nut">');
//  for (var i = 0; i < options.length; i++) {
//    html.push('<option value="' + i + '">' + options[i] + '</option>');
//  }
//  html.push('</select>');
//  document.getElementById('gifts').innerHTML = html.join('');
//}